/*
 * @Description  : 缓存方式
 * @Version      : 1.0
 * @Author       : kangshifu
 * @Date         : 2022-05-31 22:50:10
 * @LastEditors  : kangshifu
 * @LastEditTime : 2022-06-08 10:42:29
 */

const storage = {
    // 默认缓存永久
    set(key: any, value: any, type = "local"):void {
      const data = {
        value,
        createAt: new Date().getTime()
      };
      if (type === 'local') {
        window.localStorage.setItem(key, JSON.stringify(data));
      } else {
        window.sessionStorage.setItem(key, JSON.stringify(data));
      }
    },
    get(key: any, type = "local"):any {
      let data: any
      if (type === 'local') {
        data = window.localStorage.getItem(key);
      } else {
        data = window.sessionStorage.getItem(key);
      }
      data = JSON.parse(data);
      if (data !== null) {
        if (data.timer && data.createAt + data.timer <= new Date().getTime()) {
          this.remove(key, type)
        } else {
          return data.value;
        }
      }
    },
    remove(key: any, type = "local"):void {
      if (type === 'local') {
        window.localStorage.removeItem(key);
      } else {
        window.sessionStorage.removeItem(key);
      }
  
    },
    clear(type = "local"):void {
      if (type === 'local') {
        window.localStorage.clear()
      } else {
        window.sessionStorage.clear()
      }
    }
  };
  
  export default storage;